package com.cs.util;

import com.cs.domain.CSCodeRules;
import com.cs.domain.CodeRulesResult;
import com.cs.service.CSCodeRulesService;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author：bbdf
 * @Package：com.ruoyi.common.core.utils
 * @Project：RuoYi-Cloud
 * @name：CSRuleCreate
 * @Date：2024-11-13 11:07
 * @Filename：CSRuleCreate
 */
public class CSRuleCreate {
    public static CodeRulesResult GetCodeRule(CSCodeRules comCodeRules, CSCodeRulesService codeRulesService) {
        Calendar currentTime = Calendar.getInstance();
        String maxMantissa = comCodeRules.getMaxMantissa();
        int num = Integer.parseInt(maxMantissa);
        boolean b = shouldResetNum(comCodeRules, currentTime);
        if (b) {
            num = 1; // 重置为 1
            comCodeRules.setUpdateTime(currentTime.getTime());
            codeRulesService.updateComCodeRules(comCodeRules);
        } else {
            num += comCodeRules.getStep();
        }

        String reslut = String.format("%0" + comCodeRules.getSerialNumber() + "d", num);
        return computingTime(comCodeRules, reslut);
    }

    public static CodeRulesResult computingTime(CSCodeRules csCodeRules, String maxNumber) {
        String mounth = getMounth(csCodeRules.getUpdateTime().toString());
        csCodeRules.setMounth(mounth);
        String prefix = csCodeRules.getPrefix();
        Calendar calendar = Calendar.getInstance();

        if (!"".equals(csCodeRules.getYear()) && csCodeRules.getYear() != null) {
            prefix += calendar.get(Calendar.YEAR);
        }

        if (!"".equals(csCodeRules.getMounth()) && csCodeRules.getMounth() != null) {
            int month = calendar.get(Calendar.MONTH) + 1;
            prefix += String.format("%02d", month); // 确保月份格式为两位数
        }

        if (!"".equals(csCodeRules.getDay()) && csCodeRules.getDay() != null) {
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            prefix += String.format("%02d", day); // 确保日期格式为两位数
        }

        if (!"".equals(csCodeRules.getHour()) && csCodeRules.getHour() != null) {
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            prefix += String.format("%02d", hour); // 确保小时格式为两位数
        }

        if (!"".equals(csCodeRules.getMinute()) && csCodeRules.getMinute() != null) {
            int minute = calendar.get(Calendar.MINUTE);
            prefix += String.format("%02d", minute); // 确保分钟格式为两位数
        }

        if (!"".equals(csCodeRules.getSecond()) && csCodeRules.getSecond() != null) {
            int second = calendar.get(Calendar.SECOND);
            prefix += String.format("%02d", second); // 确保秒格式为两位数
        }

        prefix += maxNumber;
        CodeRulesResult codeRulesResult = new CodeRulesResult();
        codeRulesResult.setCode(prefix);
        codeRulesResult.setMax(maxNumber);
        return codeRulesResult;
    }

    public static CodeRulesResult createCode(CSCodeRulesService codeRulesService, String formName) {
        // 根据目标表单查询当前规则
        CSCodeRules codeRules = codeRulesService.selectComCodeRulesByTargetForm(formName);
        // 匹配规则
        CodeRulesResult result = CSRuleCreate.GetCodeRule(codeRules, codeRulesService);
        // 设置最大尾数
        codeRules.setMaxMantissa(result.getMax());
        //防止月份修改为数字11
        if (codeRules.getMounth().equals("11")){
            codeRules.setMounth("MM");
        }
        // 修改
        codeRulesService.updateComCodeRules(codeRules);
        return result;
    }

    public static String getMounth(String str) {
        // 创建日期格式化对象
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", java.util.Locale.ENGLISH);
        try {
            // 解析日期字符串
            Date date = sdf.parse(str);

            // 创建 Calendar 对象
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);

            // 获取月份（注意：Calendar 的月份从 0 开始，所以需要 +1）
            int month = calendar.get(Calendar.MONTH);

            // 格式化月份为两位数
            String formattedMonth = String.format("%02d", month);
            return formattedMonth;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static boolean shouldResetNum(CSCodeRules comCodeRules, Calendar currentTime) {
        Calendar lastGeneratedTime = Calendar.getInstance();
        lastGeneratedTime.setTime(comCodeRules.getUpdateTime());
        // 根据最小的单位判断是否需要重置
        if (!"".equals(comCodeRules.getYear()) && comCodeRules.getYear() != null) {
            if (lastGeneratedTime.get(Calendar.YEAR) != currentTime.get(Calendar.YEAR)) {
                return true;
            }
        }
        if (!"".equals(comCodeRules.getMounth()) && comCodeRules.getMounth() != null) {
            if (lastGeneratedTime.get(Calendar.MONTH) != currentTime.get(Calendar.MONTH)) {
                return true;
            }
        }
        if (!"".equals(comCodeRules.getDay()) && comCodeRules.getDay() != null) {
            if (lastGeneratedTime.get(Calendar.DAY_OF_MONTH) != currentTime.get(Calendar.DAY_OF_MONTH)) {
                return true;
            }
        }
        if (!"".equals(comCodeRules.getHour()) && comCodeRules.getHour() != null) {
            if (lastGeneratedTime.get(Calendar.HOUR_OF_DAY) != currentTime.get(Calendar.HOUR_OF_DAY)) {
                return true;
            }
        }
        if (!"".equals(comCodeRules.getMinute()) && comCodeRules.getMinute() != null) {
            if (lastGeneratedTime.get(Calendar.MINUTE) != currentTime.get(Calendar.MINUTE)) {
                return true;
            }
        }
        if (!"".equals(comCodeRules.getSecond()) && comCodeRules.getSecond() != null) {
            if (lastGeneratedTime.get(Calendar.SECOND) != currentTime.get(Calendar.SECOND)) {
                return true;
            }
        }
// 如果没有找到不同的时间单位，返回 false
        return false;
    }
}
